import { parentPort } from 'node:worker_threads';
import { v4 as uuid } from 'uuid';
import { taskMap } from '../src/taskMap.js';

// --------------------------------
// 以下为程序注入 header 部分代码
// --------------------------------
/**
 * DeviceManager
 */
const DeviceManager = {
    devices: [],
    tasks: {},
    createLight: (name) => {
        const device = new (function Light(name) {
            this.getSwitch = (payload) => {
                return new Promise((resolve, reject) => {
                    const id = uuid();
                    const index = DeviceManager.devices.indexOf(this);

                    const message = {
                        id,
                        type: 'method',
                        timestamp: +new Date(),
                        appInfo: globalThis.appInfo,
                        from: globalThis.appInfo.deviceList[index].id,
                        method: {
                            method: 'getSwitch',
                            methodId: 'pNnZEPxo',
                            params: {
                                value: payload,
                            },
                        },
                    };

                    DeviceManager.tasks[id] = {
                        resolve,
                        reject,
                        message,
                    };

                    parentPort.postMessage(message);
                });
            };

            this.setSwitch = (payload) => {
                return new Promise((resolve, reject) => {
                    const id = uuid();
                    const index = DeviceManager.devices.indexOf(this);

                    const message = {
                        id,
                        type: 'method',
                        timestamp: +new Date(),
                        appInfo: globalThis.appInfo,
                        from: globalThis.appInfo.deviceList[index].deviceId,
                        method: {
                            method: 'setSwitch',
                            methodId: 'peH3nfFP',
                            params: {
                                value: payload,
                            },
                        },
                    };

                    DeviceManager.tasks[id] = {
                        resolve,
                        reject,
                        message,
                    };

                    parentPort.postMessage(message);
                });
            };
        })(name);

        DeviceManager.devices.push(device);

        return device;
    },
};

globalThis.DeviceManager = DeviceManager;

/**
 * JeeWeb
 */
const JeeWeb = {
    utils: {
        isFunction: (value) => {
            return typeof value === 'function';
        },
    },
};

globalThis.JeeWeb = JeeWeb;
// --------------------------------
// 以上为程序注入 header 部分代码
// --------------------------------
